package com.neiquan.backstage.user.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neiquan.backstage.common.util.BackendErrorCode;
import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.common.util.ExtraSpringHibernateTemplate;
import com.neiquan.backstage.common.util.Paging;
import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.common.util.Strings;
import com.neiquan.backstage.pub.bsc.dao.po.AdminUser;
import com.neiquan.backstage.pub.bsc.dao.po.Entrepreneur;
import com.neiquan.backstage.pub.bsc.dao.po.User;
import com.neiquan.backstage.resourec_manage.EntrepreneurService;
import com.neiquan.backstage.user.UserService;

@Controller
@RequestMapping(value = "user", produces = { "text/json;charset=UTF-8" })
public class UserAction {
	private static Class<?> poc = User.class;
	private static Class<?> pocE =Entrepreneur.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private UserService userService;
	@Autowired
	private EntrepreneurService entrepreneurService;
	@ResponseBody
	@RequestMapping("list")
	public String list(int pageIndex, int pageSize, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<User> paging = (List<User>) extraSpringHibernateTemplate.getHibernateTemplate().find("From User where memberId=? and type=?", memberId,1);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "queryId")
	public String queryDetail(Integer id) {
		return CommonResp.buildSuccessResp(userService.queryById(id)).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "remove")
	public String remove(Integer id) {
		User toDelete = userService.queryById(id);
		if (toDelete == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().delete(toDelete);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	@ResponseBody
	@RequestMapping(value = "removeFail")
	public String removeFail(Integer userId) {
		User toDelete = userService.queryById(userId);
		if (toDelete == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		Integer memberId = toDelete.getMemberId();
		Map<String, Object> map = new HashMap<>();
		map.put("memberId", memberId);
		extraSpringHibernateTemplate.getHibernateTemplate().delete(toDelete);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "pass")
	public String pass(Integer id) {
		User toUpdateU = userService.queryById(id);
		Entrepreneur toSaveE = new Entrepreneur();
		if (toUpdateU == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		Integer memberId = toUpdateU.getMemberId();
		String entrepreneurUniqueId = toUpdateU.getEntrepreneurUniqueId();
		String entrepreneurName = toUpdateU.getEntrepreneurName();
		Entrepreneur entityE = entrepreneurService.queryByName(entrepreneurName, memberId);
		if(entityE!=null){
			return CommonResp.buildErrorResp(BackendErrorCode.entrepreneurName_repetition).toJsonString();
		}
		toSaveE.setName(entrepreneurName);
		toSaveE.setSaveTime(toUpdateU.getDtCreat());
		toSaveE.setMemberId(memberId);
		toSaveE.setStatus(0);
		toSaveE.setUniqueId(entrepreneurUniqueId);
		toSaveE.setLinkman(toUpdateU.getName());
		toSaveE.setPhone(toUpdateU.getPhone());
		if (toUpdateU.getStatus() != User.STATUS_WAIT) {
			return CommonResp.buildErrorResp(BackendErrorCode.status_error).toJsonString();
		}
		toUpdateU.setStatus(User.STATUS_PASS);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdateU);
		extraSpringHibernateTemplate.getHibernateTemplate().save(toSaveE);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "reject")
	public String reject(Integer id) {
		User toUpdate = userService.queryById(id);
		if (toUpdate == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		if (toUpdate.getStatus() != User.STATUS_WAIT) {
			return CommonResp.buildErrorResp(BackendErrorCode.status_error).toJsonString();
		}
		toUpdate.setStatus(User.STATUS_REJECT);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "search")
	public String search(String name, String phone, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", loginedUser.getMemberId()));
		criterions.add(Restrictions.eq("type", 1));
		if (StringUtils.isNoneBlank(name)) {
			criterions.add(Restrictions.like("name", "%" + name + "%"));
		}
		if (StringUtils.isNoneBlank(phone)) {
			criterions.add(Restrictions.like("phone", "%" + phone + "%"));
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("userId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}


	@ResponseBody
	@RequestMapping(value = "edit")
	public String edit(Integer id, String name, String phone, String entrepreneurName,String password) {
		User toUpdate = userService.queryById(id);
		if (null == toUpdate) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		toUpdate.setEntrepreneurName(name);
		toUpdate.setEntrepreneurName(name);
		String uniqueId = toUpdate.getEntrepreneurUniqueId();
		Integer memberId = toUpdate.getMemberId();
		Entrepreneur entityE = entrepreneurService.queryByUniqueId(uniqueId, memberId);
		entityE.setName(entrepreneurName);
		entityE.setName(entrepreneurName);
		if (StringUtils.isNoneBlank(name)) {
			toUpdate.setName(Strings.trimAndNotNull(name));
		}
		if (StringUtils.isNoneBlank(phone)) {
			toUpdate.setPhone(Strings.trimAndNotNull(phone));
		}
		if(StringUtils.isNoneBlank(password)){
			toUpdate.setPassword(Strings.trimAndNotNull(password));
		}
		extraSpringHibernateTemplate.getHibernateTemplate().update(entityE);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}
}
